<template>
  <alert :alertData="alertData" :opacity="alertOpacity" />

  <!-- 登录对话框 -->
  <!-- Place the two input before any other input to make browser auto-fill work for the two only -->
  <hwmi-dialog 
  style="width:min(400px, 90%)"
  :show="isLoginDialogShow" 
  title="登录" 
  @close="isLoginDialogShow=false">
    <div class="p-3">
      <div class="input-group">
        <span class="input-group-text" style="border-bottom-left-radius:0;">账号</span>
        <input 
        type="text" 
        class="form-control" 
        style="border-bottom-right-radius:0;" 
        placeholder="请输入账号"
        v-model="loginAccount">
      </div>

      <div class="input-group">
        <span class="input-group-text" style="border-top-left-radius:0;">密码</span>
        <input 
        type="password" 
        class="form-control" 
        style="border-top-right-radius:0;" 
        placeholder="请输入密码"
        v-model="loginPassword">
      </div>

      <div style="text-align:center;">
        <button class="btn btn-primary mt-3" style="width:200px;" @click="submitLogin">
          登录
        </button>
      </div>
    </div>
  </hwmi-dialog>

  <div class="hwmi-div-main-wrapper">
    <!--导航栏-->
    <nav class="hwmi-nav d-flex align-items-center">
      <i class="fa-solid fa-hospital fa-xl ms-3" style="color:white;"></i>

      <!-- 外层div包裹具有实际宽度的内层div，为其创建水平滑动条 -->
      <div class="hwmi-nav-links-scroll-wrapper mx-3">
        <div class="hwmi-nav-links-wrapper d-flex align-items-center">
          <router-link 
          class="hwmi-navitem" 
          :class="{'hwmi-navitem-active':$route.name==='zstp'}" 
          :to="{name:'zstp'}">知识图谱</router-link>

          <router-link 
          class="hwmi-navitem" 
          :class="{'hwmi-navitem-active':$route.name==='jbzd'}" 
          :to="{name:'jbzd'}">疾病诊断</router-link>
          
          <router-link 
          class="hwmi-navitem" 
          :class="{'hwmi-navitem-active':$route.name==='stsb'}" 
          :to="{name:'stsb'}">命名实体识别</router-link>

          <!-- <router-link 
          class="hwmi-navitem" 
          :class="{'hwmi-navitem-active':$route.name==='zscq'}" 
          :to="{name:'zscq'}">知识抽取</router-link>

          <router-link 
          class="hwmi-navitem" 
          :class="{'hwmi-navitem-active':$route.name==='blzj'}" 
          :to="{name:'blzj'}">病历质检</router-link> -->

          <router-link 
          class="hwmi-navitem" 
          :class="{'hwmi-navitem-active':$route.name==='bzgj'}" 
          :to="{name:'bzgj'}">标注工具</router-link>
        </div>
      </div>
      
      <i class="hwmi-navitem hwmi-navitem-account fa-solid fa-circle-user" 
      :class="{'hwmi-navitem-active':$route.name==='account'}" 
      @click.stop="showAccountDropdown"></i>
    </nav>

    <!--页面组件容器-->
    <div class="hwmi-div-component-area">
      <router-view v-slot="{Component}">
        <keep-alive>
          <component :is="Component" :key="$route.name" v-if="$route.meta.keepAlive"/>
        </keep-alive>

        <component :is="Component" :key="$route.name" v-if="!$route.meta.keepAlive"/>
      </router-view>
    </div>

    <!-- Account dropdown -->

    <hwmi-dropdown class="dropdown-account" 
    :style="{opacity:accountDropdownOpacity}" 
    v-show="isAccountDropdownShow">
      <div>
        <!-- Use v-if to hide in dom, adding extra safety -->
        <div class="dropdown-account-item" 
        v-if="!accountStore.isLoggedIn" 
        @click="dropdownLoginClick">登录</div>

        <div class="dropdown-account-item" 
        v-if="accountStore.isLoggedIn&&accountStore.canVisitManagement" 
        @click="dropdownCenterClick">管理中心</div>

        <div class="dropdown-account-item" 
        v-if="accountStore.isLoggedIn" 
        @click.stop="dropdownLogoutClick">退出登录</div>
      </div>
    </hwmi-dropdown>
    
  </div>
</template>

<script>
  import axios from "axios";
  import crypto from "crypto-js";

  import {useAccountStore} from "./store/AccountStore";
  import ANIMATIONS_COMMON from "./modules/AnimationsCommon";

  import {pbkdf2Salt,pbkdf2KeySize,pbkdf2Iterations} from "./modules/AppConfig.js";
  import {HWMI_URLS} from "./modules/Api";

  import Alert from "./components/Common/alert.vue";
  import HwmiDialog from "./components/Common/hwmi-dialog.vue";
  import HwmiDropdown from "./components/Common/hwmi-dropdown.vue";

  export default{
    name:"hwmiApp",
    components:{
      Alert,
      HwmiDialog,
      HwmiDropdown
    },
    setup(){
      const accountStore=useAccountStore();

      return{
        accountStore
      };
    },
    data:()=>({
      alertData: {
        show: false,
        message: "",
        type: "primary",
        },
      alertOpacity:0,
        
      isAccountDropdownShow:false,
      accountDropdownOpacity:0,
      isLoginDialogShow:false,
      loginAccount:"",
      loginPassword:""
    }),
    mounted(){
      window.onclick=this.hideAccountDropdown;

      // try to auto login
      const sessionId=localStorage.getItem("sessionId");
      
      if(sessionId===null||sessionId===""){
        return;
      }

      // suppress all errors
      axios.post(HWMI_URLS.loginRequestUrl,{
          account:"",
          passwordHashed:"",
          sessionId
        })
        .then(res=>{
          if(res.data.success){
            this.accountStore.$patch({
              isLoggedIn:true,
              account:this.loginAccount,
              level:res.data.level
            });

            this.isLoginDialogShow=false;
          }
        })
        .catch(reason=>{
          console.log(reason);
        });
      
    },
    methods:{
      showAccountDropdown(){
        if(!this.isAccountDropdownShow&&!this.isLoginDialogShow){
          ANIMATIONS_COMMON.showAccountDropdown(this);
        }
      },
      hideAccountDropdown(){
        if(this.isAccountDropdownShow){
          ANIMATIONS_COMMON.hideAccountDropdown(this);
        }
      },
      dropdownLoginClick(){
        // double check
        if(!this.accountStore.isLoggedIn){
          this.loginAccount="";
          this.loginPassword="";
          this.isLoginDialogShow=true;
        }
      },
      dropdownCenterClick(){
        if(this.accountStore.isLoggedIn&&this.accountStore.canVisitManagement){
          this.$router.push({path:"/management"});
        }
      },
      dropdownLogoutClick(){
        if(this.accountStore.isLoggedIn){
          axios.post(HWMI_URLS.logoutRequestUrl,{
            account:this.accountStore.account
          })
          .catch(reason=>{
            console.log(reason);
            ANIMATIONS_COMMON.showAlert(this,reason,"danger");
          })
          .finally(()=>{
            // here hide dropdown directly to make item change invisible
            // hide automation will not be triggered because of the .stop
            this.isAccountDropdownShow=false;
            this.accountDropdownOpacity=0;

            this.accountStore.$patch({
              isLoggedIn:false,
              account:"",
              level:0
            });
            this.$router.replace({path:"/zstp"});

            localStorage.setItem("sessionId","");
          });
        }
      },
      submitLogin(){
        if(this.loginAccount===""){
          ANIMATIONS_COMMON.showAlert(this,"请输入账号","danger");
          return;
        }

        if(this.loginPassword===""){
          ANIMATIONS_COMMON.showAlert(this,"请输入密码","danger");
          return;
        }

        const passwordHashed=
            crypto.PBKDF2(this.loginPassword,pbkdf2Salt,{
              keySize:pbkdf2KeySize,
              iterations:pbkdf2Iterations
            }).toString(crypto.enc.Base64);

        axios.post(HWMI_URLS.loginRequestUrl,{
          account:this.loginAccount,
          passwordHashed,
          sessionId:""
        })
        .then(res=>{
          if(res.data.success){
            this.accountStore.$patch({
              isLoggedIn:true,
              account:this.loginAccount,
              level:res.data.level
            });

            this.isLoginDialogShow=false;

            localStorage.setItem("sessionId",res.data.sessionId);
          }
          else{
            ANIMATIONS_COMMON.showAlert(this,"账号或密码错误","danger");
          }
        })
        .catch(reason=>{
          console.log(reason);
          ANIMATIONS_COMMON.showAlert(this,reason,"danger");
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  @import "./App";
  @import "./CommonStyles";

  .hwmi-div-main-wrapper{
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    margin: 0;

    font-family: 'Plus Jakarta Sans', sans-serif;
  }

  .hwmi-nav{
    background-color: $color-nav;
    height: $navbar-height;
    padding: 0 10px;

    user-select: none;
  }

  .hwmi-nav-links-scroll-wrapper{
    height: 100%;
    overflow-x: auto;

    @include nav-scroll-bar;
  }

  .hwmi-nav-links-wrapper{
    height: 100%;
    width: max-content;
  }

  .hwmi-navitem{
    font-size: medium;
    color: rgba(255,255,255,0.8);
    margin: 0 20px;
    
    text-decoration-line: none;

    cursor: pointer;

    transition: 150ms;

    &:hover{
      color: white;
    }
  }

  .hwmi-navitem-active{
    font-weight: bold;
    background-color: white;
    color:$color-nav;
    border-radius: 0.2em;

    // 在激活状态添加padding，可实现动效；始终添加padding则没有
    padding: 5px 10px;

    &:hover {
        color: $color-nav;
    }
  }

  .hwmi-navitem-account{
    // align right
    margin-left: auto;
    font-size: x-large;
  }

  .hwmi-div-component-area{
    width: 100%;
    height: $contentarea-height;
  }

  .dropdown-account{
    position: fixed;
    top: calc(#{$navbar-height} - 10px);
    right:5px;

    z-index: $z-index-dropdown-account;
  }

  .dropdown-account-item{
    padding: 5px 10px;

    font-size: 14px;

    // to set width without padding
    box-sizing:content-box;

    width:4em;

    color: rgb(133, 144, 166);

    cursor: pointer;

    transition-duration: 150ms;

    &:hover{
      background-color: #f6f6f6;
    }
  }
</style>
